//初始化加载折线图和表格
$(document).ready(function () {
	var type0 = 0
	var tubiaodiv0 = "tubiao0";
	loadChart(type0,tubiaodiv0);
	
	var type3 = 3
	var tubiaodiv3 = "tubiao3";
	loadChart(type3,tubiaodiv3);
	
	loadPaihangBang(0);
	
	
	$("#todayWeather").hide();
	$("#lastDayWeather").hide();
	$("#lastWeekWeather").hide();
	$(".weatherimg").hide();
	
	
})
//点击排行榜排序
$(function(){
	$(".px").click(function(){
		var id = "";
		var index = "0";
		var orderBy = "";
		var imgsrc=$(this).attr("src");
		if(imgsrc=="images/asc.png"){
			$(this).attr("src","images/desc.png");
			id = $(this).parent().siblings(".em440").attr("id");
			if(id=="paihang0"){
				index = "0";
			}else if(id=="paihang3"){
				index = "3";
			}
			orderBy = "1";
		}else{
			$(this).attr("src","images/asc.png");
			var id = $(this).parent().siblings(".em440").attr("id");
			if(id=="paihang0"){
				index = "0";
			}else if(id=="paihang3"){
				index = "3";
			}
			orderBy = "0";
		}
		parseDate("300",rankingData300,index,orderBy,id);
	});
})



var rankingData300 = null;
function saveRankDate(siteType,data){
	var indexNames = new Array();
	indexNames.push("innum");
	indexNames.push("jkl");
	indexNames.push("posStaff");
	indexNames.push("pos");
	indexNames.push("rateBags");
	indexNames.push("posInnum");
	indexNames.push("posArea");
	indexNames.push("posnum");
	indexNames.push("retentionavg");
	indexNames.push("customerNum");
	indexNames.push("newCustomerNum");
	indexNames.push("oldCustomer");
	indexNames.push("newCustomerPro");
	indexNames.push("oldCustomerPro");
	indexNames.push("returnStoreRates");
	indexNames.push("memNum");
	indexNames.push("activeUserNum");
	indexNames.push("silenceUserNum");
	indexNames.push("interNum");
	indexNames.push("newInterNum");
	indexNames.push("interAvgDuration");
	
	var data = changeStringTodouble(data,indexNames);
	if(siteType =="300"){
		rankingData300 = data;
	}
}
/**
 * 将对象的数值转为doubel类型
 * @param {Object} Object
 * @param {Object} indexNames
 */
function changeStringTodouble(Object,indexNames){
	var arr = new Array();
	arr = indexNames;
	for(var p in Object){
		for(var o in Object[p]){
			if(containsStr(arr,o)){
				var str = (Object[p])[o];
				if(str!=""&&str!=null){
					(Object[p])[o] = parseInt(str);
				}else{
					(Object[p])[o] = 0;
				}
			}
		}
	}
	
	return Object;
}

function containsStr(arr, obj) {
    var i = arr.length;  
    while (i--) {  
        if (arr[i] === obj) {  
            return true;  
        }  
    }  
    return false;  
} 
//加载排行榜
function loadPaihangBang(type) {
	var siteId	= $("#siteKey").val();
	var orderBy = "0";
	$.ajax({
		url: "getPresidentRanking",
		data: {siteId:siteId,orderBy:orderBy,type:type},
		async: true,
		success: function (result) {
			var result = result.result;
			var changsuoleix = new Array();
			for (var i = 0;i<result.length;i++){
				var siteType = result[i].siteType;//场所类型
				if(siteType =="300"){
					changsuoleix.push(siteType);
					var data = result[i].data;//数据
					saveRankDate(siteType,data);	
				}
			}
			if(changsuoleix.length == 0){
				var str = "<div class='em100 whitediv' id='zhanwushuju'><div class='em25'></div><div class='backyellow'>&nbsp;&nbsp;该场所下面没有需要排行的场所</div></div>"
				$("#divph .whitediv").children().hide();
				$("#divph .whitediv").html(str);
			}else{
				parseDate("300",data,"0","0","paihang0");
				parseDate("300",data,"3","0","paihang3");
			}
		}
	});
}
function getsiteTypeChinaName(siteType){
	var siteTypeName = "";
	switch (parseInt(siteType)) {
	case 200:
		siteTypeName = "地区";
		break;
	case 300:
		siteTypeName = "广场";
		break;
	case 400:
		siteTypeName = "区域";
		break;
	case 500:
		siteTypeName = "楼层";
		break;
	case 600:
		siteTypeName = "店铺";
		break;
	case 700:
		siteTypeName = "通道";
		break;
	default:
		break;
	}
	return 	siteTypeName;
}
function parseDate(siteType,data1,index,orderBy,paihangdiv){
	var rankingIndex = index;
	var data = data1;
	var parseDate = orderByType(rankingIndex,data,orderBy);
	var rankingIndex = rankingIndex.split(",");
	var timeModel = "日";
	/*
	指标说明选的指标的名称
	*/
	var indexAndIndexName = "";
	for (var i=0; i<rankingIndex.length ; i++) {
		var index = rankingIndex[i];
		indexAndIndexName = indexAndIndexName + array[parseInt(index)]+"("+arraydanwei[parseInt(index)]+")"+"&"
	}
	var datestr=new Date();
	datestr.setDate(datestr.getDate()-1);//获取昨天 的日期
	var strdate = 	datestr.getFullYear()+"-"+(datestr.getMonth()+1)+"-"+datestr.getDate();
	indexAndIndexName = indexAndIndexName.substring(0,indexAndIndexName.length-1);
	var	 titNamepaihang = "数据说明："+getsiteTypeChinaName(siteType)+"日指标排行"+"\n"
					+"时间范围："+strdate+"\n"
					+"场所名称："+siteN+"\n"
					+"指标名称："+indexAndIndexName;

	var zlable = new Array();
	var zlable1 = new Array();
	var zdataPer = new Array();
	var zdata = new Array();
	if(orderBy=="1"){//1升序
		for(var rank = 0; rank< rankingIndex.length; rank++){
			var index = rankingIndex[rank];
			var indexName = getOrderField(index);
			var dataPer = new Array();
			var data = new Array();
			var lable = new Array();
			var lable1 = new Array();
			var max = getFildeMaxValue(parseDate,indexName);
			for(var i = 0; i < parseDate.length; i++){
				var datei = getObjectVlue(parseDate[i],indexName);
				data.push(datei);
				lable.push(parseDate[i].sitename);
				lable1.push(parseInt(i)+1);
				var dataPeri = 0;
				if(max==""||max=="0"){
					dataPeri = 0;
				}else{
					dataPeri = parseInt(datei)/parseInt(max)*100*7/10;
				}
				dataPer.push(dataPeri);
				
			}
			zlable = lable;
			zlable1 = lable1;
			zdataPer.push(dataPer);
			zdata.push(data);
		}
	}else{//0降序
		for(var rank = 0; rank< rankingIndex.length; rank++){
			var index = rankingIndex[rank];
			var indexName = getOrderField(index);
			var dataPer = new Array();
			var data = new Array();
			var lable = new Array();
			var lable1 = new Array();
			var max =  getFildeMaxValue(parseDate,indexName);
			for(var i = 0; i < parseDate.length; i++){
				var datei = getObjectVlue(parseDate[i],indexName);
				data.push(datei);
				lable.push(parseDate[i].sitename);
				lable1.push(parseInt(i)+1);
				var dataPeri = 0;
				if(max==""||max=="0"){
					dataPeri = 0;
				}else{
					dataPeri = parseInt(datei)/parseInt(max)*100*7/10;
				}
				dataPer.push(dataPeri);
				
			}
			zlable = lable;
			zlable1 = lable1;
			zdataPer.push(dataPer);
			zdata.push(data);
		}
		lable1.reverse();
	}
	loadPaihangbang(zdata,zlable,siteType,zdataPer,zlable1,rankingIndex,paihangdiv,titNamepaihang);
}
function loadPaihangbang(data1,lable,siteType,zdataPer,lable1,rankingIndex,paihangdiv,titNamepaihang){
	var titContext =  titNamepaihang;
	var myChart = echarts.init(document.getElementById(paihangdiv));
	var data1 = eval(data1);
	var zdataPer = eval(zdataPer);
	var legendDate = new Array();
	var num =zdataPer[0].length;
	var datatemp = "";
	for(var temp=0;temp<zdataPer.length;temp++){
		var data = data1[temp];
		var dataper= zdataPer[temp]
		var paihaindex = rankingIndex[temp];
		//获取指标名称
	     var paihaIndexname = array[parseInt(paihaindex)];
		 //获取指标单位
		 var paihaZhibiaodanwei = arraydanwei[parseInt(paihaindex)];
		var values = ""; 
		for(var dp = 0;dp <data.length;dp++ ){
			values = values+"{value: "+dataper[dp]+",tooltip : {show : true,backgroundColor: 'rgba(0,0,0,0.7)',position: function(p) {return [p[0] + 10, p[1] - 10];},formatter: '"+paihaIndexname+"("+paihaZhibiaodanwei+"):"+addKannma(data[dp])+"' }},";
		}
		datatemp = datatemp + "{barMaxWidth:20, barGap:'0%',barCategoryGap:10,name:'"+array[rankingIndex[temp]]+"',type:'bar',data: ["+values+"]},";
		legendDate.push(array[rankingIndex[temp]]);
	}
	datatemp = datatemp.substring(0,datatemp.length - 1);
	datatemp = eval("["+datatemp+"]");
	var paihangwidth = $("#"+paihangdiv).width();
	var paihangheight = $("#"+paihangdiv).height();
	var lable = eval(lable);
	
//	var xAxisMax = maxDate;
	var dataZoomEnd = 0;
	var dataZoomshow = true;//是否显示数据区域，如果小于等于7就不显示
	
	if( parseInt(num)<=7){
		dataZoomshow = false;
		dataZoomEnd=0;
	}else{
		dataZoomEnd =100-(100*7/num);
	}
	dataZoomX = paihangwidth*95.73/100;
	
	if( parseInt(num)<=7){
	var Y = 100- num*(75/7);
	var gridY = Y+'%';
	}else{
		gridY = "25%";
	}
	var dataZoomY = paihangheight*(1-1/4);
	dataZoomHeight = paihangheight*94.7/100;
	titleOffens = paihangwidth*5.3/100;
	option = {
		title : {
   		      text: titContext,
   		      y:'bottom',
   		      x:titleOffens,
   		      textStyle:{
   		        fontSize: 12,
   		        color: '#666',
				fontFamily:'微软雅黑, 兰亭细黑, 宋体',
   		        fontWeight:'normal'
   		    	}		
   		    },
	    calculable : false,
	    dataZoom : {
//	    	handleColor:'rgba(68,182,234,0.8)',
//	    	fillerColor:'rgba(68,182,234,0.8)',
	      	orient:"horizontal",//horizontal,vertical
	        show : dataZoomshow,
	        realtime : true,
	        showDetail:false,
	        height: 20,
	        start : dataZoomEnd,
	        end : 100,
	        zoomLock:true,
//	        x:dataZoomX,
			y:dataZoomY
	    },
	    tooltip : {
//	    	 trigger: 'item',
	    },
	    legend: {
			y: '0%',
	        data:legendDate
	    },
	    grid: {
			x: '5.3%',
			x2: '5.3%',
	    	y:'5%',
	    	y2:gridY,
			borderWidth: gridBorderWidth,
			borderColor:'#EEE'
		},
	   yAxis : [
	        {
				 splitLine: {show: yAxisSplitLine,
					lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
		        splitArea:{
					show:yAxissplitArea,
					areaStyle:{
								color: [
						        'rgba(250,250,250,0.1)',
						        'rgba(200,200,200,0.1)']
							}
				},
	            type : 'category',
	            boundaryGap : true,
	        	splitLine:{
	        		show:false
	            },
	          	axisLabel :{
	        		show:true
	            },
	            axisTick:{
        			show:true
	        	},
	            data : lable1
	        },
	     {
	            type : 'category',
	            axisLine :{
	        		show:false
	        	},
	        	splitLine:{
	        		show:false
	            },
	            axisTick:{
        			show:false
	        	},
	        	axisLabel:{
	        		textStyle:{
	        		align:'right',
					
	        	},
	        		margin:-10,
	        		
	        	},
	            boundaryGap : true,
	            data : lable
	        }
	    ],
	    xAxis : [
	        {
				 splitLine: {show: xAxisSplitLine,
					lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
	            splitArea:{
					show:xAxissplitArea,
					areaStyle:{
							color: [
					        'rgba(250,250,250,0.1)',
					        'rgba(200,200,200,0.1)']
						}
				},
	        	axisLabel :{
        			show:false
	        	},
	        	axisTick:{
        			show:false
	        	},
	        	axisLine :{
        			show:false
        		},
	            type : 'value',
	            min:0, 
	            max:100
	        }
	    ],
	    series : datatemp
	};
	
	//改变窗口大小使图标自适应窗口显示
		window.onresize = function () {
			myChart.resize();
		}
		//加载折线图
		option.animation = false;
//		myChart.component.dataZoom.absoluteZoom(0,30);
		myChart.setOption(option);
//		myChart.clear();
		
//		myChart.setOption(option);
}


function orderByType(type,data,order){
	var order = order;//0降序；1升序
	var index ="";
	var data = data;
	if(type != ""){
		index = (type.split(","))[0];
	}
	indexName = getOrderField(index);
	if(order =="1"){//升序
		data.sort(compare1(indexName,"sitename"));
		
	}else{//降序
		data.sort(compare1(indexName,"sitename"));
		data.reverse();
	}
	return data;
}

/**
 * 定义一个比较器 
 * 使用方法
 * data.sort(compare1("name")); 
 * alert(data[0].name);//jiang
 * @param propertyName
 * @return
 */
function compare1(propertyName,name) {
	return function (object1, object2) {
		var value1 = object1[propertyName];
		var value2 = object2[propertyName];
		var name1 = object1[name];
		var name2 = object2[name];
		
		if (value2 < value1) {
			return -1;
		} 
		else if (value2 > value1) {
			return 1;
		}else if(value2 == value1){
			if (name2 < name1) {
			return -1;
			} 
			else if (name2 > name1) {
				return 1;
			}else {
				return 0;
			}
		}else {
			return 0;
		}
	}
}




//加载折线图表取XY轴
function  getXY(timeType_table,result,type) {
	var xsisRe="";
	var dataRe="";
		for(var i=0;i<result.length;i++){
			if(timeType_table=="day"||timeType_table=="hour"){
				xsisRe=xsisRe + result[i].datatime+",";
			}else if(timeType_table=="week"){
				xsisRe=xsisRe + result[i].year+"."+result[i].week +",";
			}else if(timeType_table=="month"){
				xsisRe=xsisRe + result[i].year+"."+result[i].month +",";
			}else {
				xsisRe=xsisRe + result[i].year +",";
			}
			indexNamefiled = getOrderField(type);
			 dataRe = dataRe+((getObjectVlue(result[i],indexNamefiled))==null?0:(getObjectVlue(result[i],indexNamefiled)))+",";
			
		}
	xsisRe=xsisRe.substring(0,xsisRe.length-1);
	dataRe=dataRe.substring(0,dataRe.length-1);
	var result =new Array();
	result.push(xsisRe);
	result.push(dataRe);
	return result
}

var siteN = "";
var siteName = "";
var siteTypeName = "";
//加载折线图表
 function loadChart(type,tubiaodiv) {
	 //获取指标名称
     var indexname = array[parseInt(type)];
	 //获取指标单位
	 var zhibiaodanwei = arraydanwei[parseInt(type)];
     var data = [];
     var xsis = [];
     var siteId= $("#siteKey").val();
     var tubiao = tubiaodiv
     var span = $("#txtspan").val();
     var myChart = echarts.init(document.getElementById(tubiao));
   	$.ajax( {
   		type : "GET",
   		contentType:"application/json",
   		dataType : 'json',
   		url: "presidentGraphData",
   		data: {type: type, span: span, siteId: siteId },
   		async: true,
   		success : function(ret) {
   			//下面表情的位置
   			var titleOffens = "";
   			var dataZoomY = "";;
   			var toolboxX = "";
   			siteN=ret.siteN;
			siteName = ret.siteName;
			siteTypeName = ret.siteTypeName //场所中文名称
   			var stadubiao=ret.stadubiao;
   			var endtubiao=ret.endtubiao;
   			var timeType_table = ret.timeType_table;//返回的日周月年
   			var  result = ret.result;//返回数据集
   			var xsisRe="";//X轴
   			var dataRe="";//数据线
   			var titName="";//表题
   			var resultTime ="";//原时间
   			var	timeModleName = "月";
			
			var width = $("#"+tubiaodiv).width();
			var height = $("#"+tubiaodiv).height();
			titleOffens = width*7.6/100;
			toolboxX = width*70/100;
			dataZoomY = height*(1-24/100);
			titContext="数据说明："+siteTypeName+timeModleName+"指标趋势分析"+"\n"
			+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"\n"
			+"场所名称："+siteN+"\n"
			+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
			
			var resultXY=getXY(timeType_table,result,type);
			xsisRe=resultXY[0];
			dataRe=resultXY[1];
   			
   			xsis = xsisRe.split(","); 
   			
   			/**
   			 * 横坐标只有一个值时显示为柱状图，柱状宽度最大为40
   			 */
   			var lineType = 'line';
   			if(xsis.length ==1){
   				lineType = 'bar';
   			}else{
   				lineType = 'line';
   			}
			//获取当前时间
			var date = new Date;
			var today =  timeFormat(date);
			//保存图片的名称
			var toolboxName = $("#titles").val()+'-趋势分析'+today;
   			var barMaxWidthn = 40;
   			var markLinePrecision = 0;
   			data = eval("[{name:'"+indexname+"',markLine: {precision:markLinePrecision, data: [{type: 'average',name: '平均值'}]},type:lineType,smooth: smoothType,barMaxWidth:barMaxWidthn,itemStyle:{ normal:{color:'#feab41'}},itemStyle:{normal:{label:{show:"+getShow(xsis)+",position:'top'}}},data:[" +dataRe + "]}]");
   			var  option = {
				 legend: {
			        data:[indexname]
			    },
				dataZoom: {
	   		        show: true,
					height: 20,
	   		        y:dataZoomY 
   		    	},
	   			title : {
	   		      text: titContext,
	   		      y:'bottom',
	   		      x:titleOffens,
	   		      textStyle:{
	   		        fontSize: 12,
	   		        color: '#666',
					fontFamily:'微软雅黑, 兰亭细黑, 宋体',
	   		        fontWeight:'normal'
	   		    	}		
	   		    },
			
	   			tooltip : {
	   				trigger: 'axis',
	   				backgroundColor: 'rgba(0,0,0,0.7)',
	   				position: function(p) {
	   					return [p[0] + 10, p[1] - 10];
	   				},
	   				formatter: function(params, ticket, callback) {
	   					//如果不是时间比较
						console.log(params);
						var time = "";
						var c = "";
						var time1 = "";
						var c1 = "";
	   		   			time = params[0][1];
						c = params[0][2];
	   					var a = siteName;
	   					c = addKannma(c);
	   					if (c == '') {
	   						c = 0;
	   					}
						c1 = addKannma(c1);
	   					if (c1 == '') {
	   						c1 = 0;
	   					}
						return time+'<br/>'+siteName+' : '+c;
	   				}
	   			},
	   			grid:{
	   				x:'9.6%',
					x2:'8.5%',
	   				y:'11%',
	   				y2:'31%',
	   				borderWidth: gridBorderWidth,
					borderColor:'#EEE'
	   			},
			    toolbox: {
			        show : true,
			        feature : {
			            mark : {show: true},
			            magicType : {show: true, type: ['line', 'bar']},
			            restore : {show: true},
			            saveAsImage : {
							show: true,
							name: toolboxName 
						}
			        },
			        x:toolboxX
			    },
		   		 calculable : true,
			    xAxis : [
			        {
			        	name : '日期'+'('+timeModleName+')',
			        	boundaryGap: true,//两端空白策略
			        	allowDecimals :true,//使用小数
			            type : 'category',
			            splitLine: {show: xAxisSplitLine,
						lineStyle:{
								 color: ['#EEE'],
								
							}},//不显示竖线
			            splitArea:{
							show:xAxissplitArea,
							areaStyle:{
									color: [
							        'rgba(250,250,250,0.1)',
							        'rgba(200,200,200,0.1)']
								}
						},
			            data : xsis,
			            axisTick:{
							show:true,
							interval:0
						}
			        }
			    ],
			    yAxis : [
			        {
						axisLabel:{
							formatter: function (value) {
			            		if(value >= 100000000){
									return (value/100000000)+'亿';
								}else if(value >= 10000000){
									return (value/10000000)+'千万';
								}else if(value >= 1000000){
									return (value/1000000)+'百万';
								}else if(value >= 100000){
									return (value/100000)+'十万';
								}else if(value >= 10000){
			            			return (value/10000)+'万';
			            		}else{
			            			return value + '';
			            		}
							}
						},
			        	splitLine: {
							show: yAxisSplitLine,
							lineStyle:{
								 color: ['#EEE'],
								
							}},//不显示竖线
			        	splitArea:{
							show:yAxissplitArea,
							areaStyle:{
								color: [
						        'rgba(250,250,250,0.1)',
						        'rgba(200,200,200,0.1)']
							}
						},
			        	name : indexname+'('+zhibiaodanwei+')',
			            type : 'value'
			        }
			    ],
			    series : data
			};
   			//改变窗口大小使图标自适应窗口显示
   			window.onresize = function () {
   				myChart.resize();
   			}
   			//加载折线图
   			myChart.setOption(option);
   		}
   	})
}
 